import os
from getID import *
from history2list import history2list
from translate_tree import translate_tree

def preliminary(the_id):
    getID_without_time(the_id + "_raw.json")
    #now we have sourcedata/sparse.txt and sourcedata/matrixID.json
    os.system("rm sourcedata/vector.txt")
    os.system("mv sourcedata/sparse.txt symnmfANLS/" + the_id + ".txt")
    os.chdir("symnmfANLS")
    os.system("matlab -nodesktop -r \"strs={'" + the_id + ".txt'};\" < swrun.m")
    os.chdir("..")
    os.system("rm symnmfANLS/" + the_id + ".txt")
    os.system("mv sourcedata/matrixID.json sourcedata/" + the_id + "_matrixID.json")
    list_dir = os.listdir("symnmfANLS/out")
    for fname in list_dir:
        if not fname.endswith("idx.txt"):
            continue
        str_buffer = ""
        f = open("symnmfANLS/out/" + fname)
        read_lines = f.readlines()
        f.close()
        for l in read_lines:
            l = l.strip()
            if len(l) < 8:
                continue
            A = l[0]
            B = l[2]
            C =l[-1]
            if C == '1':
                str_buffer = str_buffer + A + B + "\n"
            else:
                str_buffer = str_buffer + A + "\n"
        num_clusters = fname.split(".")[2][1:]
        f = open("sourcedata/" + the_id + "_" + num_clusters + ".txt", "w")
        f.write(str_buffer)
        f.close()
    os.system("rm -rf symnmfANLS/out/*")
    print("preliminary part finished")
